﻿using Newtonsoft.Json;
using OA.Core.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace OA.Core.Helper
{
    public static class CommonHelper
    {

        public static string ToMd5String(this string code)
        {
            using (var md5 = MD5.Create())
            {
                var result = md5.ComputeHash(Encoding.UTF8.GetBytes(code));
                var strResult = BitConverter.ToString(result);
                return strResult.Replace("-", "");
            }
        }
        public static int toInt32(this string code)
        {
            int temp = 0;
            if(Int32.TryParse(code,out temp))
            {
                return temp;
            }
            return 0;
        }
        
        public static string ToListJson(this Dictionary<string, int> dic)
        {
            List<PieData> list = new List<PieData>();
            foreach (string key in dic.Keys)
            {
                PieData item = new PieData();
                item.name = key;
                item.value = dic[key];
                list.Add(item);
            }
            list = list.OrderBy(m => m.name).ToList();
            return JsonConvert.SerializeObject(list);

        }


        public static string GetFileName(string url)
        {
            if (string.IsNullOrWhiteSpace(url)) return string.Empty;
            if(url.EndsWith("/")|| url.EndsWith("\\"))
            {
                url = url.Substring(0, url.Length - 2);
            }
            int lastIndex = url.LastIndexOf("/");
            return url.Substring(lastIndex + 1);
        }

        public static string ToString2(this DateTime? datetime)
        {
            if (datetime == null) return string.Empty;
            DateTime dt = (DateTime)datetime;
            if (dt.Year == 1) { return string.Empty; }
            return dt.ToString("yyyy-MM-dd HH:mm");
        }

        public static string ToString2(this DateTime datetime)
        {
            if (datetime.Year == 1) { return string.Empty; }
            return datetime.ToString("yyyy-MM-dd HH:mm");
        }

        public static string LastNToString(this string str, int length)
        {
            if (string.IsNullOrWhiteSpace(str) || str.Length <= length) { return str; }
            return str.Substring(str.Length - length);
        }

        public static string ToSubstring(this string str, int length)
        {
            if (string.IsNullOrWhiteSpace(str) || str.Length <= length) { return str; }
            return str.Substring(0, length);
        }

        public static string ToString3(this DateTime datetime)
        {
            if (datetime.Year == 1) { return string.Empty; }
            return datetime.ToString("yy-MM-dd HH:mm");
        }

 
        /// <summary>
        ///  
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string GetKeyList(this Dictionary<string, int> dic)
        {
            List<string> list = new List<string>();
            foreach (string key in dic.Keys)
            {
                list.Add(key);
            }
            return JsonConvert.SerializeObject(list);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string GetValueList(this Dictionary<string, int> dic)
        {
            List<int> list = new List<int>();
            foreach (string key in dic.Keys)
            {
                list.Add(dic[key]);
            }
            return JsonConvert.SerializeObject(list);

        }

        public static string NumberToString(this string number, int precision)
        {
            decimal value = 0;
            if (!decimal.TryParse(number, out value))
            {
                return number;
            }
            return value.ToString("F2");

        }

        public static string ToCmycurD(this string num)
        {
            decimal value = 0;
            if (!decimal.TryParse(num, out value))
            {
                value = 0;
            }
            return value.CmycurD();
        }


        public static string CmycurD(this decimal num)
        {
            string str1 = "零壹贰叁肆伍陆柒捌玖";            //0-9所对应的汉字
            string str2 = "万仟佰拾亿仟佰拾万仟佰拾元角分"; //数字位所对应的汉字
            string str3 = "";    //从原num值中取出的值
            string str4 = "";    //数字的字符串形式
            string str5 = "";  //人民币大写金额形式
            int i;    //循环变量
            int j;    //num的值乘以100的字符串长度
            string ch1 = "";    //数字的汉语读法
            string ch2 = "";    //数字位的汉字读法
            int nzero = 0;  //用来计算连续的零值是几个
            int temp;            //从原num值中取出的值

            num = Math.Round(Math.Abs(num), 2);    //将num取绝对值并四舍五入取2位小数
            str4 = ((long)(num * 100)).ToString();        //将num乘100并转换成字符串形式
            j = str4.Length;      //找出最高位
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出对应位数的str2的值。如：200.55,j为5所以str2=佰拾元角分

            //循环取出每一位需要转换的值
            for (i = 0; i < j; i++)
            {
                str3 = str4.Substring(i, 1);          //取出需转换的某一位的值
                temp = Convert.ToInt32(str3);      //转换为数字
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    //当所取位数不为元、万、亿、万亿上的数字时
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                }
                else
                {
                    //该位是万亿，亿，万，元位等关键位
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                        }
                    }
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    //如果该位是亿位或元位，则必须写上
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    //最后一位（分）为0时，加上“整”
                    str5 = str5 + '整';
                }
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }


        public static string ToString3(this DateTime? datetime)
        {
            if (datetime == null) return string.Empty;
            DateTime dt = (DateTime)datetime;
            if (dt.Year == 1) { return string.Empty; }
            return dt.ToString("yy-MM-dd HH:mm");
        }


        public static T GetDictionaryValueByKey<T>(Dictionary<string, T> dic, string key)
        {
            if (dic!=null&&dic.ContainsKey(key))
            {
                return dic[key];
            }

            return default(T);
        }

        /// <summary>
        /// 笛卡尔积
        /// </summary>
        /// <param name="list"></param>
        /// <param name="count"></param>
        /// <param name="result"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string Descartes(List<string[]> list, int count, List<string> result, string data, string separator)
        {
            string temp = data;
            //获取当前数组
            string[] astr = list[count];
            //循环当前数组
            foreach (var item in astr)
            {
                string myItem = item.Trim();
                if (!string.IsNullOrWhiteSpace(data) && !string.IsNullOrWhiteSpace(item.Trim()))
                {
                    myItem = separator + item.Trim();
                }
                if (count + 1 < list.Count)
                {
                    temp += Descartes(list, count + 1, result, data + myItem, separator);
                }
                else
                {
                    result.Add(data + myItem);
                }
            }
            return temp;
        }

        /// <summary>  
        /// 获取时间戳  
        /// </summary>  
        /// <returns></returns>  
        public static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }

        public static long GetTimeStamp(double second)
        {
            TimeSpan ts = DateTime.UtcNow.AddSeconds(second) - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return (long)ts.TotalSeconds;
        }

        public static int LastRandomNumber = 1000;

        public static string GetRandom2()
        {
            LastRandomNumber++;
            return LastRandomNumber.ToString();

        }

        public static string GetRandom()
        {
            Random random = new Random();
            return random.Next(10000000, 99999999).ToString();
        }

        ///<summary>
        ///生成随机字符串 
        ///</summary>
        ///<param name="length">目标字符串的长度</param>
        ///<param name="useNum">是否包含数字，1=包含，默认为包含</param>
        ///<param name="useLow">是否包含小写字母，1=包含，默认为包含</param>
        ///<param name="useUpp">是否包含大写字母，1=包含，默认为包含</param>
        ///<param name="useSpe">是否包含特殊字符，1=包含，默认为不包含</param>
        ///<param name="custom">要包含的自定义字符，直接输入要包含的字符列表</param>
        ///<returns>指定长度的随机字符串</returns>
        public static string GetRandomString(int length, bool useNum, bool useLow, bool useUpp, bool useSpe, string custom)
        {
            byte[] b = new byte[4];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetBytes(b);
            Random r = new Random(BitConverter.ToInt32(b, 0));
            string s = null, str = custom;
            if (useNum == true) { str += "0123456789"; }
            if (useLow == true) { str += "abcdefghijklmnopqrstuvwxyz"; }
            if (useUpp == true) { str += "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; }
            if (useSpe == true) { str += "!#$%&'()*+,-.:;<=>?@[]^_`{|}~"; }
            for (int i = 0; i < length; i++)
            {
                s += str.Substring(r.Next(0, str.Length - 1), 1);
            }
            return s;
        }

        public static string ToJsonString<T>(this T list)
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            string result = JsonConvert.SerializeObject(list, settings);
            return result;
        }



        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }

        public static bool IsPhone(string mobile)
        {
            if (string.IsNullOrEmpty(mobile))
                return false;
            return Regex.IsMatch(mobile, @"^1\d{10}$");
        }

       
         

        public static bool IsIDCard(string Id)
        {

            long n = 0;

            if (long.TryParse(Id.Remove(17), out n) == false || n < Math.Pow(10, 16) || long.TryParse(Id.Replace("x", "0").Replace("X", "0"), out n) == false)
            {

                return false;//数字验证

            }

            string address = "11x22x35x44x53x12x23x36x45x54x13x31x37x46x61x14x32x41x50x62x15x33x42x51x63x21x34x43x52x64x65x71x81x82x91";

            if (address.IndexOf(Id.Remove(2)) == -1)
            {

                return false;//省份验证

            }

            string birth = Id.Substring(6, 8).Insert(6, "-").Insert(4, "-");

            DateTime time = new DateTime();

            if (DateTime.TryParse(birth, out time) == false)
            {

                return false;//生日验证

            }

            string[] arrVarifyCode = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');

            string[] Wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');

            char[] Ai = Id.Remove(17).ToCharArray();

            int sum = 0;

            for (int i = 0; i < 17; i++)
            {

                sum += int.Parse(Wi[i]) * int.Parse(Ai[i].ToString());

            }

            int y = -1;

            Math.DivRem(sum, 11, out y);

            if (arrVarifyCode[y] != Id.Substring(17, 1).ToLower())
            {

                return false;//校验码验证

            }

            return true;//符合GB11643-1999标准

        }
       
        public static bool IsEmail(string email)
        {
            if (string.IsNullOrEmpty(email))
                return false;
            return Regex.IsMatch(email, @"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");
        }

        public static bool IsNumber(string number)
        {
            if (string.IsNullOrEmpty(number)) return false;
            decimal result = 0;
            if (decimal.TryParse(number, out result))
            {
                return true;
            }
            return false;
        }


        /// <summary>
        /// 判断一个字符串是否为url
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool IsUrl(string str)
        {
            try
            {
                string Url = @"^http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$";
                return Regex.IsMatch(str, Url);
            }
            catch (Exception ex)
            {
                return false;
            }
        }
 
 
    }
}
